package cn.com.wxd.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.service.attach.entity.AttachInfo;
import cn.com.wxd.service.attach.AttachConfEntity;
import cn.com.wxd.service.attach.AttachUtil;
import cn.com.wxd.common.file.FileDownLoad;

/**
 * Title:StreamServlet.java
 * Description:文件下载Servler
 * 示例：
 * 1  aaa.com/Stream/aaa/201611130000001234.jpg
 * 表示在配置paramName=aaa的路径下的文件路径为,比如aaa的路径为D:/images
 * 则：附件的真正路径为：D:/images/20161113/201611130000001234.jpg
 * <p>
 * 2  aaa.com/Stream/aaa/img/..../201611130000001234.jpg
 * 表示在配置paramName=aaa的路径下的文件路径为,比如aaa的路径为D:/images
 * 则：附件的真正路径为：D:/images/img/..../20161113/201611130000001234.jpg
 * <p>
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2015-12-28 下午7:00:03
 *
 * @author WangXuDong
 * @version 1.0
 */
public class StreamServlet extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = -7386446014813640431L;
    private static final Logger log = LoggerFactory.getLogger(StreamServlet.class);

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String requestPath = request.getRequestURI();
        /*
		 * 从请求路径获取文件地址
		 */
        AttachUtil au;
        AttachConfEntity ace;
        String file = "";//requestPath.substring(requestPath.lastIndexOf("/")+1,requestPath.length());
        String[] params = requestPath.split("/");
        String paramName =
                "";//requestPath.substring(requestPath.lastIndexOf("Stream/")+7,requestPath
		// .lastIndexOf("/"));
        try {
            //开始获取uri中隐含的参数
            for (int i = 0; i < params.length; i++) {
                if (params[i].equals("Stream")) {
                    if (i + 1 < params.length) {  //判断有没有paramName参数
                        paramName = params[i + 1];
                        if (i + 2 < params.length) { //判断有没有paramName之后的文件名及路径
                            for (int j = i + 2; j < params.length; j++) {
                                file += params[j] + File.separator;
                            }
                            file = file.substring(0, file.length() - 1);  //删除最后的一个“/”
                        } else {
                            throw new Exception("文件下载异常，参数Stream后没有paramName参数！");
                        }
                    } else {
                        throw new Exception("文件下载异常，参数Stream/paranName后没有File or FilePath参数！");
                    }
                    break;
                }
            }
            if (file.trim().equals("")) {
                return;
            }
            if (paramName == null || paramName.trim().equals("")) {
                return;
            }

            au = AttachUtil.instance();
            ace = au.getAttachConfByParamName(paramName);
            if (ace == null) {
                throw new Exception("配置文件中没有找到该param的配置！");
            }
        } catch (Exception e) {
            log.error("param参数错误，该参数不存在!", e);
            return;
        }
        String folder;
        if (!file.contains("/")) { //如果隐含的参数中没有指定文件上上层文件夹则：
            folder = file.substring(0, 8); //从文件名中提取文件所在的上一层文件夹
        } else {//指定了文件夹
            folder = file.substring(0, file.lastIndexOf(File.separator));
            file = file.substring(file.lastIndexOf(File.separator) + 1, file.length());
            folder = folder + File.separator + file.substring(0, 8);
        }
        File attach = new File(ace.getPath() + File.separator + folder + File.separator + file);
        if (!attach.exists() || attach.isDirectory()) {
            return;
        }
        if ("".equals(ace.getType()) || ace.getType() == null) {
            response.setContentType("multipart/form-data");
        } else {
            response.setContentType(ace.getType() + "/"
                    + file.substring(file.lastIndexOf(".") + 1, file.length()));
        }

        if (ace.isDownload()) {//是否支持下载
            String realFileName = file;
            if (ace.isRecorddb()) { //获取真实名称，但是获取真实名称建立在保存到数据库中
                AttachInfo attachInfo = au.getAttachInfoByDBupfileName(file);
                if (attachInfo != null && attachInfo.getFileName() != null
                        && !attachInfo.getFileName().trim().equals("")) {
                    realFileName = attachInfo.getFileName();
                }
            }
            response.setContentType("application/x-download");
            realFileName = java.net.URLEncoder.encode(realFileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + realFileName);
        }

        //获取该下载是否支持断点续传
        boolean isBpCont;
        isBpCont = ace.isBpcont();
        FileDownLoad fdl = new FileDownLoad();
        if (isBpCont) { //是否开启断点续传
            //开始断点续文件流输出
            try {
                fdl.cutPointContinutFileDownload(request, response, attach);
            } catch (IOException e) {
                log.debug("文件断点续下--暂停！" + e.getMessage());
            } catch (Exception e) {
                log.error("文件断点下载异常", e);
            }
        } else {
            //开始普通文件流输出
            try {
                fdl.fileDownload(response, attach);
            } catch (Exception e) {
                log.debug("文件流下载中断！" + e.getMessage());
            }

        }

    }

}
